﻿
/// rev.05
/// contiene la gestione di 2 seriali e la possibilità di scrivere in flasj oppure di inviare 
/// direttamente i dati al pc
/// 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Threading;



namespace MisureCelleCarico
{

    public partial class Form1 : Form
    {
        public const byte SYNC = 0xAA;
        public const byte DOWNLOAD = 0x11;
        public const byte DIRECT_CONNECT = 0x14;
        public const byte POLL = 0x10;
        public const byte GET_RELEASE = 0x80;
        public const byte CHECKSUM = 0x5B;
        public const byte SET_FLASH = 0x19;
        public const byte CLEAR_FLASH = 0x18;
        public const byte SET_SAMPLING = 0x41;

        public Form1()
        {
            InitializeComponent();
            buf1 = new byte[256];
            memFlash = new byte[128 * 1024];
            m_DataBuff = new byte[1048576];
            m_tmpReadBuff = new byte[8192];
            m_tmpReadB2 = new byte[8192];
            m_buttonState = new bool[10];
            numeroPagine = 0;
            mLineeSalvate = 0;
            Directory.SetCurrentDirectory(mPath);
            //if (!Directory.Exists("\\workArio"))
            if (!Directory.Exists(mPath + "\\testCelleCarico"))
                Directory.CreateDirectory(mPath + @"\testCelleCarico");
            mPath += "\\testCelleCarico";
            Directory.SetCurrentDirectory(mPath);
            data = new DateTime();
            MAXLINEE = 10240;
            MAXLINEE_DIRECT_DOWNLOAD = 10000;
            m_statoDirConn = false;
            m_primaPorta = m_secondaPorta = false;
            m_NewFile0 = m_NewFile1 = true;
            m_serialPpt = new SerialPort[2];
            m_serialPpt[0] = serialPort1;
            m_serialPpt[1] = serialPort2;
            m_j = 0;

        }

        /// <summary>
        ///  propeties
        /// </summary>
        int m_connectStuts = -1;
        int m_connectStuts2 = -1;       /// II port label
        byte[] buf1;                    /// local buffer
        byte[] memFlash;                /// image of flash
        int numeroPagine, m_pagLette;
        int mLineeSalvate;              /// linee fin'ora salvate
        int m_campioniScritti;
        int m_campioni2CHScritti;
        int mLinee2CHSalvate;
        int MAXLINEE;
        int MAXLINEE_DIRECT_DOWNLOAD;

        byte[] m_DataBuff;
        byte[] m_tmpReadBuff;
        byte[] m_tmpReadB2;
        bool m_statoDirConn;
        bool[] m_buttonState;
        bool m_primaPorta, m_secondaPorta;
        bool m_NewFile0, m_NewFile1;

        //string mPath = @"c:\tmp";
        string mPath = Directory.GetCurrentDirectory();
        string mFileName;
        string currDir, nome, mValore = "00";
        DateTime data;
        OpenFileDialog fileD = new OpenFileDialog();
        FileStream mFilest, mFilest_2;
        SaveFileDialog m_saveFileDialog1;
        //saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        //saveFileDialog1.ShowDialog();
        
        System.IO.Ports.SerialPort[] m_serialPpt;
        int m_j;

        /// <summary>
        /// Connect to serial port 1 and try what is available
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string nome;

            int[] statoPorta = new int[2];// = -1;
            int val, val1;
            string[] ports = SerialPort.GetPortNames();
            val = val1 = -1;
            //if (m_connectStuts != 0)
            /// not connected: we try to connect to
            //{
                if (ports.Length != 0)
                {
                    
                    for (int i = 0; i < ports.Length; i++)
                    {
                        /// prova le porte una per una
                        nome = ports[i];
                        try
                        {
                            m_serialPpt[m_j].PortName = nome;
                            m_serialPpt[m_j].BaudRate = 115200;
                            m_serialPpt[m_j].ReadTimeout = 50;
                            m_serialPpt[m_j].ReadBufferSize = 65536;
                            /// prova ad aprire la porta
                            m_serialPpt[m_j].Open();
                            statoPorta[m_j] = 0;
                            if (m_j == 0){
                                val = chiama();
                                if (val == 0)
                                {
                                    m_j++;
                                    continue;
                                }
                            
                                if (val == -2)
                                    m_serialPpt[m_j].Close();
                            }
                            if (m_j == 1){
                                /// controlla la seconda porta 
                                val1 = chiama1();
                                if (val1 == 0){
                                    m_secondaPorta = true;
                                    m_connectStuts2 = 0;
                                    m_j = 2;
                                }
                                /// se la chiamata fallisce, allora si chiude di nuovo la porta
                                if (val1 == -2){
                                    serialPort2.Close();
                                    m_secondaPorta = false;
                                    m_connectStuts2 = -1;
                                }
                            }
                        }

                        catch (SystemException sE)
                        {
                            /// la porta non esiste oppure e' gia' occupata
                            Console.WriteLine(sE.Message);
                        }

                    }
                    if (m_j >= 1)
                    {
                        label1.Text = "Connected to MCU no. 1";
                        m_connectStuts = 0;
                        button2.Enabled = true;
                        button3.Enabled = true;
                        button5.Enabled = true;
                        //button6.Enabled = true;
                        button7.Enabled = true;
                        button9.Enabled = true;
                        Console.WriteLine("Connesso MCU no. 1");
                        if (m_secondaPorta == true)
                            label1.Text += " and no. 2";
                        /// here II conn is enbabled
                        ///button10.Enabled = true;
                    }
                }
                    else
                    {
                        label1.Text = "MCU not found";
                        m_connectStuts = -1;
                        button2.Enabled = false;
                        button3.Enabled = false;
                        button5.Enabled = false;
                        //button6.Enabled = false;
                        button7.Enabled = false;
                        button9.Enabled = false;
                        
                        saveButtonState();
                    }
                    //if (statoPorta[j] == 0 && val != 0)
                    //    serialPort1.Close();
                    //if (val1 == 0)
                    //{
                    //    label2.Text = "Connected to MCU";
                    //}
                
            //}
        }

        /// <summary>
        /// Write a string on serial port and wait reply
        /// </summary>
        int chiama()
        {
            int i;
            byte v;
            byte[] buf = new byte[16];
            byte[] str = new byte[16];
            str[0] = SYNC;
            str[1] = POLL;
            serialPort1.Write(str, 0, 2);
            buf[0] = 0;
            for (i = 0; i < 2; i++)
                buf[0] += str[i];
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('S');
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('P');
            //serialPort1.Write(Convert.ToString(v));
            /// compute checksum
            buf[0] ^= CHECKSUM;
            /// and send it
            serialPort1.Write(buf, 0, 1);
            i = 0;
            do
            {
                try
                {
                    serialPort1.Read(buf, i, 1);
                    //serialPort1.Read(buf, 1, 1);
                    i++;
                }
                catch (System.Exception sE)
                {
                    Console.WriteLine(sE);
                    return -2;
                }
            }
            while (serialPort1.BytesToRead > 0);
            v = buf[0];
            v ^= CHECKSUM;
            if (buf[0] == POLL && v == buf[1])
            {
                /// we had also received the version of SW
                /// 
                v = 0;
                for (int j = 2; j < 9; j++)
                    v += buf[j];
                v ^= CHECKSUM;
                if (v == buf[9])
                {
                    /// ok, stampo il codice
                    /// 
                    string s = "fw: ";
                    for (int j = 2; j < 9; j++)
                        s += Convert.ToString(Convert.ToChar(buf[j]));
                    label3.Text += s;
                    label3.Text += "    ";

                }

                return 0;

            }

            else return -1;
        }

        /// modalita' del cazzo, xche' duplico la funzione ma la memoria e' tanta e per far prima me ne 
        /// frego delle amenita' stilistiche
        /// <summary>
        /// Write a string on serial port and wait reply
        /// </summary>
        int chiama1()
        {
            int i;
            byte v;
            byte[] buf = new byte[16];
            byte[] str = new byte[16];
            str[0] = SYNC;
            str[1] = POLL;
            serialPort2.Write(str, 0, 2);
            buf[0] = 0;
            for (i = 0; i < 2; i++)
                buf[0] += str[i];
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('S');
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('P');
            //serialPort1.Write(Convert.ToString(v));
            /// compute checksum
            buf[0] ^= CHECKSUM;
            /// and send it
            serialPort2.Write(buf, 0, 1);
            i = 0;
            do
            {
                try
                {
                    serialPort2.Read(buf, i, 1);
                    //serialPort1.Read(buf, 1, 1);
                    i++;
                }
                catch (System.Exception sE)
                {
                    Console.WriteLine(sE);
                    return -2;
                }
            }
            while (serialPort2.BytesToRead > 0);
            v = buf[0];
            v ^= CHECKSUM;
            if (buf[0] == POLL && v == buf[1])
            {
                /// we had also received the version of SW
                /// 
                v = 0;
                for (int j = 2; j < 9; j++)
                    v += buf[j];
                v ^= CHECKSUM;
                if (v == buf[9])
                {
                    /// ok, stampo il codice
                    /// 
                    string s = " fw: ";
                    for (int j = 2; j < 9; j++)
                        s += Convert.ToString(Convert.ToChar(buf[j]));
                    label3.Text += s;


                }

                return 0;

            }

            else return -1;
        }

        /// <summary>
        /// Donwload the data from the I2C eeprom on the board
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            int i;
            byte v;
            byte[] buf1 = new byte[256];
            byte[] str = new byte[4];

            if (m_connectStuts != 0)
                return;
            /// imposto le pagine gia' lette
            m_pagLette = numeroPagine;
            bool fineCiclo = false;
            for (int contatorePagine = m_pagLette;
                //(contatorePagine < 512 + m_pagLette) && (fineCiclo == false); 
                (contatorePagine < 1024 + m_pagLette) && (fineCiclo == false);
                contatorePagine++)
            {
                str[0] = SYNC;
                str[1] = DOWNLOAD;
                serialPort1.Write(str, 0, 2);
                buf1[0] = 0;
                for (i = 0; i < 2; i++)
                    buf1[0] += str[i];
                //serialPort1.Write(Convert.ToString(v));
                //v += Convert.ToByte('S');
                //serialPort1.Write(Convert.ToString(v));
                //v += Convert.ToByte('P');
                //serialPort1.Write(Convert.ToString(v));
                /// compute checksum
                buf1[0] ^= CHECKSUM;
                /// and send it
                serialPort1.Write(buf1, 0, 1);
                i = 0;
                v = 0;
                do
                {
                    try
                    {
                        serialPort1.Read(buf1, i, 1);
                        i++;
                    }
                    catch (System.Exception sE)
                    {
                        Console.WriteLine(sE);
                        return;
                    }
                }
                while (i < 2);
                v = buf1[0];
                v ^= CHECKSUM;
                if (buf1[0] == DOWNLOAD && v == buf1[1])
                {
                    /// ok, the command's echo is arrived
                    /// I may read all flash...1024 pages
                    /// 

                    /// we pass all pages on the flash memory
                    i = 0;
                    v = 0;
                    do
                    {
                        try
                        {
                            serialPort1.Read(buf1, i, 1);
                            //serialPort1.Read(buf, 1, 1);
                            //v += buf1[i];
                            i++;
                        }
                        catch (System.Exception sE)
                        {
                            Console.WriteLine(sE);
                            return;
                        }
                    }
                    while (i < 129);
                    for (int j = 0; j < i - 1; j++)
                        v += buf1[j];
                    v ^= CHECKSUM;
                    if (v == buf1[i - 1])
                    {
                        /// this block is ok.
                        /// 
                        Console.WriteLine("block {0}  ok", contatorePagine);
                        textBox2.Text = Convert.ToString(contatorePagine);
                        richTextBox2.Text = Convert.ToString(contatorePagine);
                        string s = "";
                        int sommaControllo = 0;
                        for (i = 0; i < 128; i++)
                        {
                            sommaControllo += buf1[i];
                            s += "\t" + Convert.ToString(buf1[i]);
                            if (contatorePagine >= 1024)
                                fineCiclo = true;
                            else
                            {
                                /// copy of a page
                                memFlash[contatorePagine * 128 + i] = buf1[i];
                            }

                        }
                        richTextBox1.Text += s + "\n";
                        /// evita di stampare la pagina di 255 caricata come
                        /// ultima e necessaria a capire che e' una pagina di memoria
                        /// non utilizzata
                        if (sommaControllo == 255 * 128)
                        {
                            fineCiclo = true;
                        }
                        else
                            /// aggiorno il numero di pagine gia' lette purche' 
                            /// quella attuale diversa da 255 ripetuto 128 volte
                            numeroPagine = contatorePagine + 1;

                    }

                }
                /// we finished to read all flash content
                /// we can write data on a file or copy the rich box contents on excel

            }
        }

        /// <summary>
        /// Disconnect to port
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (m_connectStuts == 0)
            {
                /// alreay connect: we can disconnect
                /// 
                m_connectStuts = -1;
                serialPort1.Close();
                if (m_connectStuts2 == 0)
                    serialPort2.Close();
                label1.Text = "Not connected";
                button2.Enabled = false;
                button3.Enabled = false;
                button5.Enabled = false;
                button7.Enabled = false;
                button9.Enabled = false;
                Console.WriteLine("Disconnessa MCU");
                label3.Text = "";
                label6.Text = "";
                m_j = 0;
                
            }


        }

        /// <summary>
        /// imposta la flash a 255
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            int i;
            byte v;
            byte[] buf = new byte[2];
            byte[] str = new byte[4];
            str[0] = SYNC;
            str[1] = SET_FLASH;
            serialPort1.Write(str, 0, 2);
            buf[0] = 0;
            for (i = 0; i < 2; i++)
                buf[0] += str[i];
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('S');
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('P');
            //serialPort1.Write(Convert.ToString(v));
            /// compute checksum
            buf[0] ^= CHECKSUM;
            /// and send it
            serialPort1.Write(buf, 0, 1);
            i = 0;
            do
            {
                try
                {
                    serialPort1.Read(buf, i, 1);
                    //serialPort1.Read(buf, 1, 1);
                    i++;
                }
                catch (System.Exception sE)
                {
                    Console.WriteLine(sE);
                    return;
                }
            }
            while (serialPort1.BytesToRead > 0);
            v = buf[0];
            v ^= CHECKSUM;
            if (buf[0] == SET_FLASH && v == buf[1])
            {
                Console.WriteLine("ricevuto set flash");
                return;
            }

            else
            {
                Console.WriteLine("set non ricevuto ");
                return;
            }
        }

        /// <summary>
        /// clear the flash
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            int i;
            byte v;
            byte[] buf = new byte[2];
            byte[] str = new byte[4];
            str[0] = SYNC;
            str[1] = CLEAR_FLASH;
            serialPort1.Write(str, 0, 2);
            buf[0] = 0;
            for (i = 0; i < 2; i++)
                buf[0] += str[i];
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('S');
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('P');
            //serialPort1.Write(Convert.ToString(v));
            /// compute checksum
            buf[0] ^= CHECKSUM;
            /// and send it
            serialPort1.Write(buf, 0, 1);
            i = 0;
            do
            {
                try
                {
                    serialPort1.Read(buf, i, 1);
                    //serialPort1.Read(buf, 1, 1);
                    i++;
                }
                catch (System.Exception sE)
                {
                    Console.WriteLine(sE);
                    return;
                }
            }
            while (serialPort1.BytesToRead > 0);
            v = buf[0];
            v ^= CHECKSUM;
            if (buf[0] == CLEAR_FLASH && v == buf[1])
            {
                Console.WriteLine("ricevuto reset flash");
                return;
            }
            else
            {
                Console.WriteLine("reset non ricevuto");
                return;
            }

        }

        /// <summary>
        /// save a data file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[3];
            char[] carattere = new char[128];
            byte[] buf1 = new byte[10];
            UTF8Encoding utf8 = new UTF8Encoding();
            Stream myStream;
            int a;
            //buffer[0] = Convert.ToByte('A');
            //buffer = new UTF8Encoding(true).GetBytes("pippo");
            saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {

                /// aperto il file e fornito un nome si devono salvare i file con 
                /// numerazione progeressiva
                /// 
                String s = saveFileDialog1.FileName, s2;
                nome = s;
                mPath = s;
                /// azzera il numero di linee salvate, in modo da produrre il nome 
                /// del primo file del blocco
                mLineeSalvate = 0;
                /// scrive i dati su file    
                for (int np = 0; np < numeroPagine; np++){
                    ///controlla se deve iniziare il nuovo file e produce il nome
                    if (mLineeSalvate == 0)
                    {
                        do
                        {
                            a = s.LastIndexOf("\\");
                            if (a != 0)
                            {
                                s = s.Substring(a);
                                mPath = mPath.Substring(0, a);
                            }
                        }
                        while (a != 0);
                        /// estrazione del nome: tolgo .txt
                        a = s.IndexOf(".");
                        s2 = s.Insert(a, mValore);
                        s = nome;
                        /// estratto il nome si può continuare a scrivere tutti i dati.
                        data = DateTime.Now;
                        /// composizione : mese_giorno_nomeXX.txt
                        s2 = s2.Insert(1, data.Day + "_" + data.Month + "_" + data.Hour + "_" + data.Minute + "_" + data.Second + "_");
                        a = Convert.ToInt32(mValore) + 1;
                        if (a < 10)
                            mValore = Convert.ToString(0);
                        else
                            mValore = "";
                        mValore += Convert.ToString(a);

                        mFilest = File.Create(mPath + s2);
                    }
                    /// page byte
                    for (int i = 0; i < 128; i++)
                    {
                        //string s = Convert.ToString(memFlash[i]);
                        buf1 = utf8.GetBytes(Convert.ToString(memFlash[np * 128 + i]));
                        mFilest.Write(buf1, 0, buf1.Length);
                        /// va a capo ogni riga.
                        /// arrivati a 10000 linee va a capo

                        string s1 = "\n";
                        buffer = utf8.GetBytes(s1);
                        mFilest.Write(buffer, 0, buffer.Length);
                        mLineeSalvate++;
                        if (mLineeSalvate >= MAXLINEE)
                        {
                            /// 40 blocchi da 256 valori ciascuno
                            mLineeSalvate = 0;
                            mFilest.Close();
                        }
                    }
                }
                /// chiude forzatamente l'ultimo file
                mFilest.Close();
            }
        }


        /// <summary>
        ///  clear the contents of rich boxtext
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            numeroPagine = 0;
            m_pagLette = 0;

        }

        /// <summary>
        /// set the sampling time on the board
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            byte[] buf = new byte[3];
            byte[] str = new byte[4];
            for (int i = 0; i < m_j; i++)
            {
                buf[0] = SYNC;
                buf[1] = SET_SAMPLING;
                buf[2] = buf[0];
                buf[2] += buf[1];
                buf[2] ^= CHECKSUM;
                try
                {
                    m_serialPpt[i].Write(buf, 0, 3);
                }
                catch (System.Exception s)
                {
                    Console.WriteLine(s.Message);
                }

                /// trasmissione dato
                /// 
                try
                {
                    buf[0] = Convert.ToByte(textBox1.Text);
                }
                catch (System.Exception s)
                {
                    buf[0] = 255;
                    textBox1.Text = "255";
                }
                buf[1] = CHECKSUM;
                buf[1] ^= buf[0];

                try
                {
                    m_serialPpt[i].Write(buf, 0, 2);
                }
                catch (System.Exception s)
                {
                    Console.WriteLine(s.Message);
                }

            }


        }

        /// <summary>
        /// per scopi di debug.
        /// Permette di riempire le 128*1024 locazioni a caso
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {
            Random rnd = new Random();
            //for (int i = 0; i < 128 * 1024; i++)
            //{
            //    memFlash[i] = Convert.ToByte(rnd.Next(0, 255));
            //}
            for (int i = 0; i < 1024 * 1024; i++)
            {
                m_DataBuff[i] = Convert.ToByte(rnd.Next(0, 255));
            }
       
            numeroPagine = 1024;
        }

        /// <summary>
        /// riceve continuamente i dati dalla scheda di acquisizione.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e){
            int i;
            byte v;
            byte[] buf1 = new byte[10];
            byte[] str = new byte[4];

            //if (m_connectStuts != 0)
              //  return;

            if (m_statoDirConn){
                this.button9.BackColor = System.Drawing.Color.LightGreen;
                m_statoDirConn = false;
                restoreButtonState();
                this.timer1.Enabled = false;
                /// chiude l'ultimo file eventualmente ancora aperto
                try{
                    mFilest.Close();
                    m_NewFile0 = true;
                }
                catch (System.Exception se){
                    Console.WriteLine("already closed");
                }
                if (m_j == 2)
                    try
                    {
                        mFilest_2.Close();
                        m_NewFile1 = true;
                    }
                    catch (System.Exception se)
                    {
                        Console.WriteLine("already closed");
                    }
            }
            else{
                /// open file dialog window
                m_saveFileDialog1 = new SaveFileDialog();
                m_saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                saveButtonState();
                if (m_saveFileDialog1.ShowDialog() == DialogResult.OK){
                    /// si salva il nome del file in cui salvare i dati
                    /// 
                    mFileName = m_saveFileDialog1.FileName;
                    /// dovrebbe disabilitare tutti i tasti, tranne button9
                    saveButtonState();
                    this.button9.BackColor = System.Drawing.Color.Salmon;
                    m_statoDirConn = true;
                    saveButtonState();
                    disableAllButton();

                }
                else {
                    restoreButtonState();
                    this.button9.BackColor = System.Drawing.Color.LightGreen;
                    m_statoDirConn = false;
                    return;
                }
                mLineeSalvate = 0;
                m_campioniScritti = 0;
                m_campioni2CHScritti = 0;
                mLinee2CHSalvate = 0;
            }

            bool fineCiclo = false;
            /// send DIRECT_CONNECT to 1^ board
            str[0] = SYNC;
            str[1] = DIRECT_CONNECT;

            try{
                m_serialPpt[0].Write(str, 0, 2);
            }
            catch (System.Exception sE){
                Console.WriteLine(sE);
            }
            /// build command....
            buf1[0] = 0;
            for (i = 0; i < 2; i++)
                buf1[0] += str[i];
            /// compute checksum
            buf1[0] ^= CHECKSUM;
            /// and send it
            try{
                m_serialPpt[0].Write(buf1, 0, 1);
            }
            catch (System.Exception sE){
                Console.WriteLine(sE);
                Console.WriteLine("riposo");
                System.Threading.Thread.Sleep(800);
            }
            i = v = 0;
            /// read reply from the board 1
            do{
                try{
                    m_serialPpt[0].Read(buf1, i, 1);
                    i++;
                }
                catch (System.Exception sE){
                    Console.WriteLine(sE);
                    return;
                }
            }
            while (i < 2);
            //while (false);
            
            v = buf1[0];
            v ^= CHECKSUM;
            if (buf1[0] == DIRECT_CONNECT && v == buf1[1])
                m_primaPorta = true;
            ///
            /// try SECOND PORT, if present
            /// 
            if (m_j == 2) {
                str[0] = SYNC;
                str[1] = DIRECT_CONNECT;

                try{
                    m_serialPpt[1].Write(str, 0, 2);
                }
                catch (System.Exception sE){
                    Console.WriteLine(sE);
                }
                /// build command....
                buf1[0] = 0;
                for (i = 0; i < 2; i++)
                    buf1[0] += str[i];
                /// compute checksum
                buf1[0] ^= CHECKSUM;
                /// and send it
                try{
                    m_serialPpt[1].Write(buf1, 0, 1);
                }
                catch (System.Exception sE){
                    Console.WriteLine(sE);
                    Console.WriteLine("riposo");
                    System.Threading.Thread.Sleep(800);
                }
                i = v = 0;
                /// read reply from the board 2
                do{
                    try{
                        m_serialPpt[1].Read(buf1, i, 1);
                        i++;
                    }
                    catch (System.Exception sE){
                        Console.WriteLine(sE);
                        return;
                    }
                }
                while (i < 2);
                v = buf1[0];
                v ^= CHECKSUM;
                if (buf1[0] == DIRECT_CONNECT && v == buf1[1])
                    m_secondaPorta = true;
            }

            /// if first port isn't present 
            if (m_primaPorta){
                /// arrivato qui fa partire il timer che ogni 200 ms legge i campioni inviati
                /// 
                if (m_statoDirConn){
                    /// start the timer will trigger acquisition
                    this.timer1.Enabled = true;
                    mLineeSalvate = 0;
                    m_campioniScritti = 0;
                }
                else{
                    this.timer1.Enabled = false;
                    /// conviene svuotare i buffer per eventuali usi successivi
                    /// 
                    bool continua = true;
                    while (continua)
                      try
                        {
                            m_serialPpt[0].Read(m_tmpReadBuff, 0, 8100);
                        }
                        catch (System.Exception sE)
                        {
                            //Console.WriteLine(sE);
                            Console.WriteLine("buffer lettura vuoto");
                            /// data lost, we'll try again
                            //return;
                            continua = false;
                        }

                    continua = true;
                    while (continua)
                        try
                        {
                            m_serialPpt[1].Read(m_tmpReadBuff, 0, 8100);
                        }
                        catch (System.Exception sE)
                        {
                            //Console.WriteLine(sE);
                            Console.WriteLine("buffer lettura vuoto");
                            /// data lost, we'll try again
                            //return;
                            continua = false;
                        }
                    
                }
            }
            else { 
            /// svuota il buffer per un uso successivo
                bool continua = true;
                while (continua){
                    try{
                        m_serialPpt[0].Read(m_tmpReadBuff, 0, 8100);
                    }
                    catch (System.Exception sE){
                        //Console.WriteLine(sE);
                        Console.WriteLine("buffer lettura vuoto");
                        /// data lost, we'll try again
                        //return;
                        continua = false;
                    }
                    try{
                        m_serialPpt[1].Read(m_tmpReadBuff, 0, 8100);
                    }
                    catch (System.Exception sE){
                        //Console.WriteLine(sE);
                        Console.WriteLine("buffer lettura vuoto");
                        /// data lost, we'll try again
                        //return;
                        continua = false;
                    }
                }
            }
        }

        /// <summary>
        /// timer 1 event: read serial buffer every 0.5s
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            int bytesDaLegg = 0;
            int i, k;
            UTF8Encoding utf8 = new UTF8Encoding();
            byte[] buffer = new byte[3];

            bool cont = true;
            bool cont2 = true;
            /// read a block of 200 samples
            /// 
            /// j say if one or two ports are present
            i = k = 0;
            while (i < 500 && cont){
                try{
                    /// firts port is surely present
                    bytesDaLegg = m_serialPpt[0].Read(m_tmpReadBuff, i, 500);
                    //serialPort1.Read(buf, 1, 1);
                    //v += buf1[i];
                    i += bytesDaLegg;
                }
                catch (System.Exception sE)
                {
                    //Console.WriteLine(sE);
                    Console.WriteLine("buffer lettura vuoto");
                    /// data lost, we'll try again
                    //return;
                    cont = false;
                    /// deve essere multiplo di 3
                    //i -= i % 3;
                }
            }
            /// lettura secondo buffer, se esiste
            /// 
            if (m_j == 2)
                while(k < 600 && cont2)
                {
                    try { 
                        bytesDaLegg = serialPort2.Read(m_tmpReadB2 , k, 600);
                        k += bytesDaLegg;
                    }
                    catch(System.Exception sE){
                        Console.WriteLine("buffer 2 lettura vuoto");
                        cont2 = false;
                        /// deve essere multiplo di 3
                        //k -= k % 3;
                    }

                }
        
            if (i > 0 || (m_j == 2 && k > 0))
            {
                /// terminato il blocco, andrebbe salvato
                /// 
                //String s = "C:\\Users\\massimo\\Documents\\proveIRAM\\cacheBlock.txt", s2;
                //String s = "\\cacheBlock.txt", s2;
                int a;
                String s2, s3;
                nome = mFileName;
                mPath = mFileName;
                /// azzera il numero di linee salvate, in modo da produrre il nome 
                /// del primo file del blocco
                
                //numeroPagine = 1024;
                /// scrive i dati su file    
                //for (int np = 0; np < numeroPagine; np++){
                    ///controlla se deve iniziare il nuovo file e produce il nome
                do{
                    //if (mLineeSalvate == 0){
                    if (m_NewFile0 == true || (m_j == 2 && m_NewFile1 == true))
                        scriviIntestazioneFile();
                    
                    /// write the i bytes just read SISTEMARE QUI LA SCRITTURA SU FILE
                    for ( int j= 0; j < i; j++){
                        int tValore;
                        
                        // devo sincronizzare il valore con 0x5A
                        /// 
                        //if (m_tmpReadBuff[j] == 0x5A) {


                        //    tValore = (m_tmpReadBuff[j + 1] << 8) + m_tmpReadBuff[j + 2];
                        //    if (m_tmpReadBuff[j + 3] >= Convert.ToInt32(textBox3.Text))
                        //    {
                        //        //string s = Convert.ToString(memFlash[i]);
                        //        //buf1 = utf8.GetBytes(Convert.ToString(m_campioniScritti));
                        //        buf1 = utf8.GetBytes(Convert.ToString(tValore));
                        //        mFilest.Write(buf1, 0, buf1.Length);
                        //        string s1 = "\t\t";
                        //        buffer = utf8.GetBytes(s1);
                        //        mFilest.Write(buffer, 0, buffer.Length);

                        //        buf1 = utf8.GetBytes(Convert.ToString(m_tmpReadBuff[j + 2]));
                        //        mFilest.Write(buf1, 0, buf1.Length);
                        //        /// va a capo ogni riga.
                        //        /// arrivati a 10000 linee chiude il file e ne crea uno nuovo

                        //        s1 = "\n";
                        //        buffer = utf8.GetBytes(s1);
                        //        mFilest.Write(buffer, 0, buffer.Length);
                        //        mLineeSalvate++;
                        //        if (mLineeSalvate >= MAXLINEE_DIRECT_DOWNLOAD)
                        //        {

                        //            mLineeSalvate = 0;
                        //            mFilest.Close();
                        //            /// occorre riallineare le celle non scritte di tmpReadBuffer
                        //            /// e ricordarsi di "buttare" i primi tre campioni, perche' gia' presi
                        //            /// colò giro precedente (infatti j non e' stato ancora incrementato
                        //            j += 3;
                        //            for (int alfa = 0; alfa < i - j; alfa++)
                        //                m_tmpReadBuff[alfa] = m_tmpReadBuff[alfa + j];
                        //            i = i - j;
                        //            /// e completare la scrittura
                        //            break;
                        //        }
                        //    }
                            
                        
                            
                            
                            
                        //    /*                 *****     */
                        //}
                       
            
                        
                        /// 
                        /// formato dei campioni: num * 256 + num1 + valore campione
                        /// 

                        tValore = (m_tmpReadBuff[j] << 8) + m_tmpReadBuff[j + 1];
                        //if (m_tmpReadBuff[j * 3 + 2] >= Convert.ToInt32(textBox3.Text))
                        if (m_tmpReadBuff[j] >= Convert.ToInt32(textBox3.Text))
                        {
                            String s1 = " ";
                            
                            m_campioniScritti++;
                            if (m_campioniScritti % 1000 == 0)
                            {
                                data = DateTime.Now;
                                s1 = s1.Insert(1, "time \t\t" + data.Hour + ":" + data.Minute + ":" + data.Second + "." + data.Millisecond + "\n");
                                buf1 = utf8.GetBytes(s1);
                                mFilest.Write(buf1, 0, buf1.Length);

                            }

                            //string s = Convert.ToString(memFlash[i]);
                            buf1 = utf8.GetBytes(Convert.ToString(m_campioniScritti));
                            //buf1 = utf8.GetBytes(Convert.ToString(tValore));
                            mFilest.Write(buf1, 0, buf1.Length);
                            s1 = "\t\t";
                            buffer = utf8.GetBytes(s1);
                            mFilest.Write(buffer, 0, buffer.Length);

                            buf1 = utf8.GetBytes(Convert.ToString(m_tmpReadBuff[j]));
                            mFilest.Write(buf1, 0, buf1.Length);
                            /// va a capo ogni riga.
                            /// arrivati a 10000 linee chiude il file e ne crea uno nuovo

                            s1 = "\n";
                            buffer = utf8.GetBytes(s1);
                            mFilest.Write(buffer, 0, buffer.Length);
                            mLineeSalvate++;
                            if (mLineeSalvate >= MAXLINEE_DIRECT_DOWNLOAD)
                            {

                                mLineeSalvate = 0;
                                mFilest.Close();
                                m_NewFile0 = true;
                                /// occorre riallineare le celle non scritte di tmpReadBuffer
                                /// e ricordarsi di "buttare" i primi tre campioni, perche' gia' presi
                                /// colò giro precedente (infatti j non e' stato ancora incrementato
                                j += 1;
                                for (int alfa = 0; alfa < i - j; alfa++)
                                    m_tmpReadBuff[alfa] = m_tmpReadBuff[alfa + j];
                                i = i - j;
                                /// e completare la scrittura
                                break;
                            }
                        }
                    }


                    if (m_j == 2){
                        /// write on second files only if second channel exist
                        for (int j = 0; j < k; j++){

                            string s1 = " ";
                            m_campioni2CHScritti++;

                            if (m_campioni2CHScritti % 1000 == 0)
                            {
                                data = DateTime.Now;
                                s1 = s1.Insert(1, "time \t\t" + data.Hour + ":" + data.Minute + ":" + data.Second + "." + data.Millisecond + "\n");
                                buf1 = utf8.GetBytes(s1);
                                mFilest_2.Write(buf1, 0, buf1.Length);

                            }
                            

                            if (m_tmpReadB2[j] >= Convert.ToInt32(textBox3.Text)){
                                //string s = Convert.ToString(memFlash[i]);
                                buf1 = utf8.GetBytes(Convert.ToString(m_campioni2CHScritti));
                                mFilest_2.Write(buf1, 0, buf1.Length);
                                s1 = "\t\t";
                                buffer = utf8.GetBytes(s1);
                                mFilest_2.Write(buffer, 0, buffer.Length);

                                buf1 = utf8.GetBytes(Convert.ToString(m_tmpReadB2[j]));
                                mFilest_2.Write(buf1, 0, buf1.Length);
                                /// va a capo ogni riga.
                                /// arrivati a 10000 linee chiude il file e ne crea uno nuovo

                                s1 = "\n";
                                buffer = utf8.GetBytes(s1);
                                mFilest_2.Write(buffer, 0, buffer.Length);
                                mLinee2CHSalvate++;
                                if ((mLinee2CHSalvate >= MAXLINEE_DIRECT_DOWNLOAD) || 
                                    (mLineeSalvate >= MAXLINEE_DIRECT_DOWNLOAD))
                                {

                                    mLinee2CHSalvate = 0;
                                    mFilest_2.Close();
                                    m_NewFile1 = true;
                                    /// occorre riallineare le celle non scritte di tmpReadBuffer
                                    for (int alfa = 0; alfa < k - j; alfa++)
                                        m_tmpReadB2[alfa] = m_tmpReadB2[alfa + j];
                                    k = k - j;
                                    /// e completare la scrittura
                                    break;
                                }
                            }
                        }
                    }
                    int pippabauda = 0;
                } while (mLineeSalvate == 0);
                //}
                /// chiude forzatamente l'ultimo file
                ///mFilest.Close();
            }
               
        //}
                     
            
        }

        /// <summary>
        /// save the buttons state
        /// </summary>
        private void saveButtonState() {

            m_buttonState[0] = this.button1.Enabled;
            m_buttonState[1] = this.button2.Enabled;
            m_buttonState[2] = this.button3.Enabled;
            m_buttonState[3] = this.button4.Enabled;
            m_buttonState[4] = this.button5.Enabled;
            m_buttonState[5] = this.button6.Enabled;
            m_buttonState[6] = this.button7.Enabled;
            m_buttonState[7] = this.button8.Enabled;
            m_buttonState[8] = this.button9.Enabled;
            
        
        }

        /// <summary>
        /// restore the buttons state
        /// </summary>
        private void restoreButtonState() {
            this.button1.Enabled = m_buttonState[0];
            this.button2.Enabled = m_buttonState[1];
            this.button3.Enabled = m_buttonState[2];
            this.button4.Enabled = m_buttonState[3];
            this.button5.Enabled = m_buttonState[4];
            this.button6.Enabled = m_buttonState[5];
            this.button7.Enabled = m_buttonState[6];
            this.button8.Enabled = m_buttonState[7];
            this.button9.Enabled = m_buttonState[8];
            
        }

        /// <summary>
        /// disable all buttons except button 9 (direct connection)
        /// </summary>
        private void disableAllButton() {
            this.button1.Enabled = false;
            this.button2.Enabled = false;
            this.button3.Enabled = false;
            this.button4.Enabled = false;
            this.button5.Enabled = false;
            this.button6.Enabled = false;
            this.button7.Enabled = false;
            this.button8.Enabled = false;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            /// if a file is again open, close it before exit
            try
            {
                mFilest.Close();
            }
            catch (System.Exception se) {
                Console.WriteLine("Ciao, file gia' chiuso");
            }
        }

        
        /// <summary>
        /// informazione della versione
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void infoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Versione corrente:\n5.0\nby Hilltech", "indicazione della versione",
            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        /// <summary>
        /// this method answer to request to second connection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button10_____Click(object sender, EventArgs e)
        {

            string nome;
            int statoPorta = -1;
            int val, val1;
            string[] ports = SerialPort.GetPortNames();
            val = val1 = -1;
            
            /// prova le porte una per una
            for (int i = 0; i < ports.Length; i++){
                nome = ports[i];
                serialPort2.PortName = nome;
                serialPort2.BaudRate = 115200;
                serialPort2.ReadTimeout = 50;
                try
                {

                    /// prova ad aprire la porta
                    serialPort2.Open();
                    statoPorta = 0;
                }

                catch (SystemException sE)
                {
                    /// la porta non esiste
                    Console.WriteLine(sE.Message);
                }

                /// write on port
                if (statoPorta == 0)
                {
                    val1 = chiama1();
                    if (val1 == 0)
                    {
                        /// controlla la seconda porta (se presente)
                        /// 
                        i = ports.Length + 1;
                        m_secondaPorta = true;
                        label6.Text = "connessa MCU 2";
                        m_connectStuts2 = 0;
                    }
                    if (val1 == -2)
                    {
                        serialPort2.Close();
                        statoPorta = -1;
                        m_secondaPorta = false;
                        m_connectStuts2 = -1;
                    }
                }
            }
        }     
    }
}
